<template>
  <div class="log-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>操作日志列表</h3>
        </div>
      </template>

      <el-form :model="searchForm" :inline="true" @submit.prevent="searchLogs">
        <el-form-item label="请选择类型">
          <el-select v-model="searchForm.action" placeholder="请选择类型" style="width: 120px">
            <el-option label="全部类型" value=""></el-option>
            <el-option
              v-for="action in actionTypes"
              :key="action"
              :label="action"
              :value="action"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="昵称/操作数据id">
          <el-input
            v-model="searchForm.keywords"
            placeholder="昵称/操作数据id"
            style="width: 300px"
          />
        </el-form-item>

        <div class="button-container">
          <el-button type="primary" @click="searchLogs">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">清空</el-button>
          <el-button @click="handleMove">移动至</el-button>
          <el-button @click="handleUpload">上传文件</el-button>
          <el-button @click="handleBatchDelete" type="danger">批量删除</el-button>
        </div>
      </el-form>

      <el-table :data="logList" border v-loading="loading" :height="tableHeight">
        <el-table-column prop="id" label="ID号" width="90" align="center" />
        <el-table-column prop="action" label="操作日志名称" width="80" align="center" />
        <el-table-column prop="content" label="操作描述" width="200" />
        <el-table-column prop="param_id" label="操作数据ID" width="100" align="center" />
        <el-table-column prop="param" label="操作详细数据信息">
          <template #default="scope">
            <div class="param-content">
              <div class="param-text">
                <el-tooltip
                  effect="dark"
                  placement="top"
                  :hide-after="0"
                  :show-after="100"
                  popper-class="param-tooltip"
                  v-if="scope.row.param && scope.row.param.length > 50"
                >
                  <template #content>
                    <div class="tooltip-content">
                      {{ scope.row.param }}
                    </div>
                  </template>
                  <span>{{ truncateText(scope.row.param, 50) }}</span>
                </el-tooltip>
                <span v-else>{{ scope.row.param }}</span>
              </div>
              <div class="param-action">
                <el-button
                  v-if="scope.row.param && scope.row.param.length > 50"
                  type="primary"
                  size="small"
                  link
                  @click="showDetailDialog(scope.row)"
                >
                  查看完整数据
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="ip" label="IP地址" width="130" align="center" />
        <el-table-column prop="create_time" label="操作时间" width="160" align="center" />
      </el-table>

      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </el-card>

    <!-- 详细数据对话框 -->
    <el-dialog v-model="detailDialogVisible" title="详细数据信息" width="700px">
      <div class="detail-content">
        <pre>{{ currentDetailData }}</pre>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Search } from '@element-plus/icons-vue'
  import { getLogList as getLogListApi, getActionTypes as getActionTypesApi } from '@/api/home/log'

  // 数据相关
  const logList = ref<any[]>([])
  const loading = ref(false)
  const tableHeight = ref(window.innerHeight - 200)

  // 详细数据对话框
  const detailDialogVisible = ref(false)
  const currentDetailData = ref('')

  // 操作类型
  const actionTypes = ref<string[]>([])

  // 搜索表单
  const searchForm = reactive({
    action: '',
    keywords: '',
  })

  // 分页
  const pagination = reactive({
    currentPage: 1,
    pageSize: 20,
    total: 0,
  })

  // 获取日志列表
  const getLogs = async () => {
    try {
      loading.value = true
      const response = await getLogListApi({
        page: pagination.currentPage,
        limit: pagination.pageSize,
        action: searchForm.action,
        keywords: searchForm.keywords,
      })

      // 确保数据格式正确
      if (response && response.data) {
        // 处理分页数据结构 {"code":0,"msg":"获取成功","data":{"list":[],"count":0}}
        if (response.data.list && Array.isArray(response.data.list)) {
          // 检查关键字段是否存在
          const validatedData = response.data.list.map((item: any) => {
            return {
              id: item.id || '',
              action: item.action || '',
              content:
                item.content ||
                (item.user_name
                  ? item.user_name + ' ' + item.action + '了 ' + (item.subject || '')
                  : ''),
              param_id: item.param_id || item.paramId || '',
              param: item.param || item.param_formatted || '',
              ip: item.ip || '',
              create_time: item.create_time || item.create_time_format || '',
            }
          })
          logList.value = validatedData
          pagination.total = response.data.count || response.data.list.length || 0
        }
        // 处理直接数组结构
        else if (Array.isArray(response.data)) {
          const validatedData = response.data.map((item: any) => {
            return {
              id: item.id || '',
              action: item.action || '',
              content:
                item.content ||
                (item.user_name
                  ? item.user_name + ' ' + item.action + '了 ' + (item.subject || '')
                  : ''),
              param_id: item.param_id || item.paramId || '',
              param: item.param || item.param_formatted || '',
              ip: item.ip || '',
              create_time: item.create_time || item.create_time_format || '',
            }
          })
          logList.value = validatedData
          pagination.total = response.data.length || 0
        }
        // 处理无分页的单对象结构
        else if (typeof response.data === 'object' && response.data !== null) {
          // 如果是单个对象，转换为数组
          const dataAsArray = [response.data]
          const validatedData = dataAsArray.map((item: any) => {
            return {
              id: item.id || '',
              action: item.action || '',
              content:
                item.content ||
                (item.user_name
                  ? item.user_name + ' ' + item.action + '了 ' + (item.subject || '')
                  : ''),
              param_id: item.param_id || item.paramId || '',
              param: item.param || item.param_formatted || '',
              ip: item.ip || '',
              create_time: item.create_time || item.create_time_format || '',
            }
          })
          logList.value = validatedData
          pagination.total = 1
        } else {
          console.warn('Log list data format is incorrect:', response.data)
          logList.value = []
          pagination.total = 0
        }
      } else {
        console.warn('Log list data is empty')
        logList.value = []
        pagination.total = 0
      }
    } catch (error: any) {
      console.error('Failed to fetch log list:', error)
      ElMessage.error('获取日志列表失败: ' + (error.message || '未知错误'))
      logList.value = []
      pagination.total = 0
    } finally {
      loading.value = false
    }
  }

  // 获取操作类型列表
  const getActionTypes = async () => {
    try {
      const response = await getActionTypesApi()

      if (response.code === 0 && response.data && response.data.type_actions) {
        // 将对象转换为数组格式
        actionTypes.value = Object.keys(response.data.type_actions)
      } else {
        actionTypes.value = []
      }
    } catch (error) {
      // 忽略错误
      actionTypes.value = []
      console.warn('获取操作类型列表失败:', error)
    }
  }

  // 搜索日志
  const searchLogs = () => {
    pagination.currentPage = 1
    getLogs()
  }

  // 重置搜索
  const resetSearch = () => {
    searchForm.action = ''
    searchForm.keywords = ''
    pagination.currentPage = 1
    getLogs()
  }

  // 处理分页大小变化
  const handleSizeChange = (val: number) => {
    pagination.pageSize = val
    pagination.currentPage = 1
    getLogs()
  }

  // 处理当前页变化
  const handleCurrentChange = (val: number) => {
    pagination.currentPage = val
    getLogs()
  }

  // 文本截断函数
  const truncateText = (text: string, length: number) => {
    if (!text) return ''
    if (text.length <= length) return text
    return text.substring(0, length) + '...'
  }

  // 显示详细数据对话框
  const showDetailDialog = (row: any) => {
    try {
      // 尝试格式化JSON数据
      const paramData = row.param
      if (
        typeof paramData === 'string' &&
        (paramData.startsWith('{') || paramData.startsWith('['))
      ) {
        try {
          const parsedData = JSON.parse(paramData)
          currentDetailData.value = JSON.stringify(parsedData, null, 2)
        } catch {
          currentDetailData.value = paramData
        }
      } else {
        currentDetailData.value = paramData
      }
    } catch (error) {
      currentDetailData.value = row.param || ''
    }
    detailDialogVisible.value = true
  }

  // 移动至功能
  const handleMove = () => {
    ElMessage.info('移动至功能待实现')
  }

  // 上传文件功能
  const handleUpload = () => {
    ElMessage.info('上传文件功能待实现')
  }

  // 批量删除功能
  const handleBatchDelete = () => {
    ElMessageBox.confirm('确定要批量删除选中的日志吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        ElMessage.success('批量删除成功')
      })
      .catch(() => {
        ElMessage.info('已取消删除')
      })
  }

  // 初始化
  onMounted(() => {
    getLogs()
    getActionTypes()

    // 监听窗口大小变化
    window.addEventListener('resize', () => {
      tableHeight.value = window.innerHeight - 200
    })
  })
</script>

<style scoped>
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  /* 表单样式 */
  .el-form {
    display: flex;
    flex-wrap: wrap;
    align-items: flex-start;
  }

  .el-form-item {
    margin-bottom: 18px;
    margin-right: 10px;
  }

  .el-form-item:last-child {
    margin-right: 0;
  }

  .button-container {
    display: flex;
    align-items: center;
    flex-wrap: nowrap;
    margin-top: 10px;
    margin-bottom: 10px;
  }

  .button-container .el-button {
    margin-right: 10px;
  }

  .button-container .el-button:last-child {
    margin-right: 0;
  }

  .pagination {
    margin-top: 20px;
    text-align: right;
  }

  .param-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }

  .param-text {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-right: 10px;
  }

  .param-action {
    flex-shrink: 0;
    width: 120px;
    text-align: right;
  }

  .detail-content {
    max-height: 400px;
    overflow-y: auto;
    background-color: #f5f7fa;
    padding: 10px;
    border-radius: 4px;
  }

  .detail-content pre {
    white-space: pre-wrap;
    word-break: break-word;
    font-family: monospace;
    margin: 0;
  }

  /* 添加到style标签外部，针对全局样式 */
</style>

<style>
  /* 定制Tooltip样式 */
  .param-tooltip {
    max-width: 80vw !important;
    word-break: break-all !important;
  }

  .tooltip-content {
    max-width: 500px;
    max-height: 300px;
    overflow: auto;
    word-break: break-all;
    white-space: pre-wrap;
  }
</style>
